#coding=utf-8
'''
@author: tongji
@contact: tongji@rekoo.com
'''
import sys
import time
import datetime
now = datetime.datetime.now

def basecallback(request):
    '''取基础数据, 请勿修改'''
    data = {}
    data['uid'] = request.user.id
    data['num'] = 1 # num设置默认值
    data['ts'] = time.strftime('%H:%M:%S')
    return data


class Logger(object):
    '''日志对象'''
    def __init__(self):
        self.formatter = ['ts', 'uid', 'scene', 'level', 'stay', 'action', 'v1', 'v2', 'v3', 'v4', 'num']
        self.resetstatus()
        self.output = sys.stdout.write # 默认标准输出
    
    def get_data_before(self, request):
        self.status['before']['first_name'] = request.user
    
    def get_data_after(self, request, basecallback=basecallback, callback=None, funcname=None):
        if basecallback: # 取到基础数据
            self.status['after'] = basecallback(request)
            self.status['after']['action'] = funcname
        if callback: # 设置完固定参数后，看有没有附加的记录（v1, v2, v3, v4, num）
            extradata = callback(request)
            self.status['after'].update(extradata)
    
    def format(self, data): #格式化数据
        delimiter = '\t'
        record = []
        for item in self.formatter:
            record.append(data.get(item, None))
        return delimiter.join(map(str, record))
    
    def write(self): # 将数据写到规定的渠道
        try:
            record = self.format(self.status['after'])
        except Exception,e:
            print e
        else:
            self.output(record)
            
    def setoutput(self, output_handler = None): #设置输出方式
        if output_handler:
            self.output = output_handler
        else:
            self.output = sys.stdout.write
        
    #重置数据
    def resetstatus(self):          
        self.status = { #'global' :{},
                        'before' :{},
                        'after' :{},
                        #'exception' :{},
        }
